<!-- 首页 -->
<template>
	<view class="home-wrap u-m-b-20">
		<!-- 空白页 -->
		<!-- #ifdef APP-PLUS -->
		<u-no-network @retry="init"></u-no-network>
		<!-- #endif -->
		<shopro-empty
			v-if="!hasTemplate"
			:image="$IMG_URL + '/imgs/empty/template_empty.png'"
			tipText="暂未找到模板，请前往装修~"
		></shopro-empty>

		<view v-else-if="isConnected && isRefresh" class="content-box">
			<!-- 导航栏 -->
			<!-- :scrollTop="scrollTop" -->
			<home-head
				v-if="headSwiperList && headSwiperList.length"
				
				borderRadius="0"
				:navTitle="initShop.name"
				:list="headSwiperList"
				:homeListData="homeList"
				ref="headHome"
			></home-head>
			<!-- 自定义模块 -->
			<view class="template-box">
				<block v-for="(item, index) in homeTemplate" :key="item.id">
					<!-- 轮播 -->
					<template v-if="!flag_big">
						<sh-banner
							v-if="item.type === 'banner' && index !== 0"
							:Px="item.content.x"
							:Py="item.content.y"
							:borderRadius="item.content.radius"
							:height="item.content.height"
							:list="item.content.list"
						></sh-banner>
					</template>
					

					<!-- 搜索 -->
					<sh-search v-if="item.type === 'search'"></sh-search>

					<!-- 滑动宫格 -->
					<sh-grid-swiper
						v-if="item.type === 'menu'"
						:list="item.content.list"
						:oneRowNum="item.content.style"
					></sh-grid-swiper>

					<!-- v-if="!flag_big" -->
					<!-- <template > -->
						<!-- 推荐商品 -->
						<sh-hot-goods
							v-if="item.type === 'goods-list' || item.type === 'goods-group'" ref="usernameInput"
							:detail="item.content" :ind="pageFather"
						></sh-hot-goods>
						<!-- 广告魔方 -->
						<sh-adv v-if="item.type === 'adv'" :detail="item.content"></sh-adv>
						<!-- 优惠券 -->
						<sh-coupon v-if="item.type === 'coupons'" :detail="item.content"></sh-coupon>
						<!-- 秒杀-->
						<sh-seckill v-if="item.type === 'seckill'" :detail="item.content"></sh-seckill>
						<!-- 拼团 -->
						<sh-groupon v-if="item.type === 'groupon'" :detail="item.content"></sh-groupon>
						<!-- 富文本 -->
						<sh-richtext v-if="item.type === 'rich-text'" :richId="item.content.id"></sh-richtext>
						<!-- 功能标题 -->
						<sh-title-card
							v-if="item.type === 'title-block'"
							:title="item.content.name"
							:bgImage="item.content.image"
							:titleColor="item.content.color"
						></sh-title-card>
					<!-- </template> -->
					<!-- 推荐商品 -->
					<!-- <sh-hot-goods
						v-if="flag_big"
						:detail="item.content"
					></sh-hot-goods> -->
					<!-- 直播 -->
					<!-- #ifdef MP-WEIXIN -->
					<sh-live v-if="item.type === 'live' && HAS_LIVE" :detail="item.content"></sh-live>
					<!-- #endif -->
				</block>
			</view>

			<template v-if="!flag_big">
					<!-- 分类选项卡 -->
					<sh-category-tabs
						v-if="categoryTabsData && categoryTabsData.category_arr && categoryTabsData.category_arr.length"
						:enable="enable"
						:styleType="categoryTabsData.style"
						:tabsList="categoryTabsData.category_arr"
					></sh-category-tabs>				
			</template>
			
			<!-- 登录提示 -->
			<shopro-auth-modal @childEvent="resetHomeList"></shopro-auth-modal>
			<!-- 悬浮按钮 -->
			<!-- <shopro-float-btn></shopro-float-btn> -->
			<!-- 连续弹窗提醒 -->
			<shopro-notice-modal v-if="!showPrivacy && isLogin"></shopro-notice-modal>
			<!-- 隐私协议 -->
			<!-- #ifdef APP-PLUS -->
			<privacy-modal v-if="initShop && initShop.name" v-model="showPrivacy"></privacy-modal>
			<!-- #endif -->
			<!-- #ifdef H5 -->
			<view class="tabbar-hack" style="height: 120rpx; width:100%;"></view>
			<!-- #endif -->
		</view>
		<!-- <shopro-tabbar></shopro-tabbar> -->
		<view @click="FLAG_BIG" class="test_btn">
			<text>{{flag_big?'关爱':'普通'}}
			模式</text>
			<!-- <text>模式</text> -->
		</view>
		<view v-if="flag_big" class="yuyinBOX" @touchstart="startRecording" @touchend="stopRecording">
			<image :src="$IMG_URL+'/static/images/index_top/yuyin.png'" mode=""></image>
			<text>按住说话搜一搜</text>
		</view>
		<view class="yuyinLoding" v-show="showyyLoding">
			<nest-jumping-spectrum :sWidth="500" :spectrumHeightMax="100" ref="jumpingSpectrum"></nest-jumping-spectrum>
		</view>
		 
	</view>
</template>

<script>
import shBanner from './components/sh-banner.vue';
import shGridSwiper from './components/sh-grid-swiper.vue';
import shHotGoods from './components/sh-hot-goods.vue';
import shAdv from './components/sh-adv.vue';
import shCoupon from './components/sh-coupon.vue';
import shSeckill from './components/sh-seckill.vue';
import shGroupon from './components/sh-groupon.vue';
import shRichtext from './components/sh-richtext.vue';
import shTitleCard from './components/sh-title-card.vue';
import shSearch from './components/sh-search.vue';
import shCategoryTabs from './components/sh-category-tabs.vue';
import privacyModal from './index/privacy-modal.vue';
import homeHead from './index/home-head.vue';
	import http from '@/shopro/request/index'
// #ifdef MP-WEIXIN
import { HAS_LIVE } from '@/env';
import shLive from './components/sh-live.vue';
// #endif
const recorderManager = uni.getRecorderManager();
const innerAudioContext = uni.createInnerAudioContext();
	
import { mapMutations, mapActions, mapState, mapGetters } from 'vuex';
export default {
	components: {
		shBanner,
		shGridSwiper,
		shGroupon,
		shHotGoods,
		shAdv,
		shCoupon,
		shSeckill,
		shRichtext,
		shTitleCard,
		shSearch,
		shCategoryTabs,

		privacyModal,
		homeHead,

		// #ifdef MP-WEIXIN
		shLive
		// #endif
	},
	data() {
		return {
			// #ifdef MP-WEIXIN
			HAS_LIVE: HAS_LIVE,
			// #endif
			isRefresh: true,
			pageFather:'indexPage',
			text: 'uni-app',
			voicePath: '',
			enable: false, //是否开启吸顶。
			isConnected: true, //是否有网
			showPrivacy: false, //协议
			scrollTop: 0,
			YYdata:'',
			showyyLoding:false,
			showPoup:false,
			homeList:[]
		};
	},
	computed: {
		...mapGetters(['initShop', 'homeTemplate', 'hasTemplate', 'isLogin']),
		// 头部模块数据
		headSwiperList() {
			if (this.homeTemplate?.length) {
				console.log('首页模板数据',this.homeTemplate);
				return this.homeTemplate[0]?.content?.list;
			}
		},
		// 分类选项卡数据
		categoryTabsData() {
			if (this.homeTemplate?.length) {
				// console.log('????',this.homeTemplate);
				return this.homeTemplate[this.homeTemplate.length - 1]?.content;
			}
		},
		// 是否为大字版
		flag_big(){
			return this.$store.state.user.isBIG
		}
	},
	onPullDownRefresh() {
		this.init();
	},
	onPageScroll(e) {
		this.scrollTop = e.scrollTop;
	},
	onReachBottom() {
		console.log(this.$refs.usernameInput);
		this.$refs.usernameInput[0].btommFun()
		// this.childFun()
	},
	onShow() {
		// this.init();
		http('user.homeList').then(res=>{
			console.log(res);
			// this.waitList = res.data.auditList
			let homeListData = res.data.userFamilyList
			// this.waitList = res.data.filter(it=>{
			// 	if(it.status==0){
			// 		return it
			// 	}
			// })
			// this.hasList = res.data.filter(it=>{
			// 	if(it.status==1){
			// 		return it
			// 	}
			// })
			this.homeList = homeListData.filter(item=>{
				if(item.status==1){
					return item
				}
			})
			console.log('家属列表',this.homeList);
		})
		// this.$refs.headHome.inputEnter('')
		let that = this;
		// this.$refs.headHome.resetList()
		this.enable = true;
		this.isLogin && this.getCartList();
		// 网络变化检测
		uni.onNetworkStatusChange(res => {
			this.isConnected = res.isConnected;
			res.isConnected && this.init();
		});
		console.log(this.$store.state);
		let self = this;
		// console.log(this.$refs.headHome);
		// self.$refs.headHome.resetList()
		recorderManager.onStop(function (res) {
					// console.log('recorder stop' + JSON.stringify(res));
					console.log('录音管理器数据',res);
					self.voicePath = res.tempFilePath;
					console.log(self.voicePath);
					// innerAudioContext.autoplay = true;
					innerAudioContext.src = self.voicePath;
					uni.uploadFile({
								url: 'https://xiaolao.edeapp.com/addons/shopro/asr.identify/index', //仅为示例，非真实的接口地址
								// header: {
								//     'token': self.$store.state.user.token
								//   },
								filePath: self.voicePath,
								name: 'file',
								success: (uploadFileRes) => {
									// innerAudioContext.play()
									// console.log(uploadFileRes);
									// self.$refs.headHome.inputEnter('')
									console.log('接口返回语音识别数据',uploadFileRes.data);
									let nData = JSON.parse(uploadFileRes.data)
									console.log('赋值后数据',nData.data);
									uni.hideLoading()
									// self.YYdata = uploadFileRes.data.data
									self.$refs.headHome.inputEnter(nData)
								},
								fail:(rrs) =>{
									console.log('上传失败',rrs);
								},
								complete: (rre) => {
									console.log('上传结束',rre);
									
								}
							});
				});
				recorderManager.onError(function(errdata){
					console.log('错误信息',errdata);
				} )
	},
	onHide() {
		this.enable = false;
		this.$refs.headHome.reset()
	},
	onLoad() {
		// #ifdef APP-VUE
		// plus.runtime.disagreePrivacy();
		console.log(plus.runtime.isAgreePrivacy(), 1111111111);
		// app隐私协议弹窗
		if (!plus.runtime.isAgreePrivacy()) {
			this.showPrivacy = true;
			this.showNoticeModal = false;
		}
		// #endif
		
					
	},
	
	methods: {
		// 在需要判断权限的地方调用该方法
		checkRecordPermission() {
		  uni.getSetting({
		    success: (res) => {
		      if (!res.authSetting['scope.record']) {
		        // 用户未授权录音权限，显示提示弹窗
				return false
		      } else {
				  return true
			  }
		    }
		  });
		},

		childFun(){
			// this.$refs.list_goods.btommFun();
			this.$emit('btommFun');
		},
		...mapActions(['appInit', 'getTemplate', 'getCartList']),
		...mapMutations(['FLAG_BIG']),
		// 初始化
		init() {
			this.isRefresh = false;
			return Promise.all([this.getTemplate()]).then(() => {
				uni.stopPullDownRefresh();
				this.isRefresh = true;
			});
		},
		resetHomeList(){
			// this.init();
			http('user.homeList').then(res=>{
				console.log('首页登录组件触发',res);
				// this.waitList = res.data.auditList
				let homeListData = res.data.userFamilyList
				// this.waitList = res.data.filter(it=>{
				// 	if(it.status==0){
				// 		return it
				// 	}
				// })
				// this.hasList = res.data.filter(it=>{
				// 	if(it.status==1){
				// 		return it
				// 	}
				// })
				this.homeList = homeListData.filter(item=>{
					if(item.status==1){
						return item
					}
				})
				console.log('家属列表',this.homeList);
			})
		},
		 startRecording() {
			 // if(this.checkRecordPermission()){
				 this.showyyLoding = true
				 this.$refs.jumpingSpectrum.startJumping();
				 console.log('开始录音1');
				 		  recorderManager.start({
				          format: 'wav',
				          // format: 'PCM',
				 					  // format:'pcm',
				          // format: 'mp3',
				 					  sampleRate:16000,
				 					  encodeBitRate:96000,
				 					  // frameSize:50,
				 					  numberOfChannels:1,
				 					  duration:60000,
				          success: (res) => {
				            console.log('开始录音2', res);
				            // 可以在开始录音成功后进行一些操作，如更新状态或界面
				          },
				          fail: (err) => {
				            console.error('开始录音失败', err);
				          }
				        });
			 // } else {
				 // uni.showModal({
				 //          title: '提示',
				 //          content: '需要获取录音权限才能继续操作',
				 //          confirmText: '去授权',
				 //          success: (res) => {
				 //            if (res.confirm) {
				 //              // 用户点击确认按钮，跳转到权限设置页
				 //              uni.openSetting();
				 //            }
				 //          }
				 //        });
			 // }
			 
		    },
		    stopRecording() {
				 this.showyyLoding = false
				 this.$refs.jumpingSpectrum.stopJumping();
				 uni.showLoading({
				 	title:'识别中'
				 })
				 console.log('录音结束函数');
			 	recorderManager.stop(res=>{
					console.log('录音结束函数',res);
							// this
				});
		    },
			 uploadAudio(filePath) {
				 console.log('??录音');
				 uni.showModal({
				 	content:filePath
				 })
			      // 调用接口上传录音文件
			      // 根据实际需求使用 uni.uploadFile 或其他网络请求方法上传文件
			    }
		// checkBB(){
		// 	console.log('切换版本');
		// 	FLAG_BIG()
		// }
	}
};
</script>

<style lang="scss">
	.yuyinLoding {
		 height: 175rpx;
		        display: flex;
		        align-items: center;
		            position: fixed;
		            left: 50%;
		            transform: translateX(-50%);
		            justify-content: center;
		            bottom: 20%;
					background-color: rgb(137,217,97);
					border-radius: 15px;
					padding: 0 15px;
	}
	.yuyinBOX {
		position: fixed;
		left: 50%;
		// bottom: 7.5vh;
		bottom: calc(var(--window-bottom) + 120rpx);
		// right: 30rpx;
		transform: translateX(-50%);
		height: 47px;
			background-image: linear-gradient(0deg, 
				#ffd0bc 0%, 
				#ffe5da 100%), 
			linear-gradient(
				#ffd3c2, 
				#ffd3c2);
			background-blend-mode: normal, 
				normal;
			box-shadow: 0px 6px 18px 0px 
				rgba(0, 0, 0, 0.38);
			border-radius: 23px;
			border: solid 2px #ffffff;
			display: flex;
			align-items: center;
			justify-content: center;
				padding: 0 30px;
			image {
				width: 15px;
				height: 20px;
			}
			text {
				margin-left: 15px;
				font-size: 20px;
					font-weight: bold;
				white-space: nowrap;
				color: #ff3400;
			}
	}
	
	.test_btn {
		width: 45px;
		height: 45px;
		position: fixed;
		// bottom: 1vh;
		// right: 12px;
		bottom: calc(var(--window-bottom) + 120rpx);
		right: 30rpx;
		    // background-color: blue;
		opacity: 0.8;
		font-size: 12px;
		color: rgb(255, 255, 255);
		// padding: 10px;
		border-radius: 50%;
		background-color: #000000;
		opacity: 0.6;
		// text-align: center;
		// line-height: 45px;
		font-weight: bold;
		display: flex;
		align-items: center;
		justify-content: center;
		// line-height: 18px;
	}
	.box_list_BIG {
		padding: 0 5px;
		box-sizing: border-box;
		.cell_BIG {
			display: flex;
			justify-content: space-between;
			.cell_l {
				width: 45%;
				image {
					max-height: 170px;
				}
			
			}
			.cell_r {
				flex: 1;
				margin-left: 10px;
				text {
					display: block;
				}
				.title_cell {
					font-size: 22px;
					font-weight: bold;
					color: #000;
				}
				.price_cell {
					color: #ff0000;
					font-size: 20px;
					font-weight: bold;
					b {
						font-size: 28px;
					}
					
				}
				.num_cell {
					font-size: 20px;
					font-weight: normal;
					color: #ff0000;
				}
			}
		}
	}
</style>
